package com.atguigu.gulimall.auth.web;

import cn.hutool.json.JSONUtil;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @create: 2024/9/7
 * @author: gyhe10
 * @description:
 **/

@Slf4j
@Controller
public class OAuth2Controller {

    @Resource
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weiboLogin(@RequestParam("code") String code, HttpSession session, RedirectAttributes redirectAttributes) throws Exception {
        // 构造请求参数
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "1852662691");
        map.put("client_secret", "41f8a75325da3c60f93980f0548c0f87");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);

        // 发送 POST 请求获取 Access Token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "POST", new HashMap<>(), map, new HashMap<>());

        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到社交登录用户令牌，转为通用社交登录响应模型类对象
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSONUtil.toBean(json, SocialUser.class);
            // 远程调用 member 服务进行登录
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode() == 0) {
                Object object = r.get("data");
                MemberResponseVo memberResponseVo = JSONUtil.toBean(JSONUtil.toJsonStr(object), MemberResponseVo.class);
                System.out.println("通过微博实现社交登录，用户信息 = " + memberResponseVo);
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberResponseVo);
                // 登录成功，重定向到首页
                return "redirect:http://gulimall.com";
            } else {
                // 远程调用 member 服务的社交登录接口失败，封装错误提示信息，返回登录页
                Map<String, String> errors = new HashMap<>();
                errors.put("msg", r.get("msg").toString());
                redirectAttributes.addFlashAttribute("errors", errors);
                // 远程调用失败，重定向到登录页
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            // 向微博认证服务器获取令牌失败，封装错误提示信息，返回登录页
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", response.getStatusLine().getReasonPhrase());
            redirectAttributes.addFlashAttribute("errors", errors);
            // 登录失败，重定向到登录页
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
